// 用户相关的状态管理
import { createSlice } from '@reduxjs/toolkit'
import { request, getToken, setToken as _setToken, removeToken } from '@/utils';
import { loginAPI, getProfileAPI } from '@/apis/user';

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        userInfo: {

        },
        token: getToken() || '',
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
});

// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer
const userReducer = userStore.reducer

// 封装异步方法
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        // 编写异步逻辑
        const res = await loginAPI(loginForm);
        // 调用dispatch函数提交action
        dispatch(setToken(res.data.token));
    }
}

// 获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        // 编写异步逻辑
        const res = await getProfileAPI();
        // 调用dispatch函数提交action
        dispatch(setUserInfo(res.data));
    }
}

export {
    setToken,
    fetchLogin,
    fetchUserInfo,
    clearUserInfo
}

export default userReducer
